package com.lsm.czxxgl_system.controller;

import com.lsm.czxxgl_system.constant.UserConstant;
import com.lsm.czxxgl_system.model.domain.User;
import com.lsm.czxxgl_system.model.request.UserLoginRequest;
import com.lsm.czxxgl_system.model.request.UserSearchRequest;
import com.lsm.czxxgl_system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: UserController
 * Package: com.lsm.czxxgl_system.controller
 * Description:
 *
 * @Author lsm
 * @Create 2024/6/25 11:33
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public String userLogin(UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest, Model model) {
        //判断用户名或密码是否为空
        String userPassword = userLoginRequest.getUserPassword();
        String username = userLoginRequest.getUsername();
        if (StringUtils.isAnyBlank(userPassword,username)) {
            model.addAttribute("error_msg","用户名或密码不能为空");
            return "login";
        }
        //根据用户名和密码查询用户
        User user = userService.userLogin(username, userPassword,httpServletRequest);
        //判断用户是否存在
        if (user == null) {
            //用户不存在，返回到登录页,并设置错误信息
            model.addAttribute("error_msg","用户名或密码错误");
            return "login";
        }
        return "redirect:/main";
    }

    @GetMapping("/list")
    public String list(HttpServletRequest httpServletRequest,Model model) {
        //验证角色权限 是否为管理员
        if (!isAdmin(httpServletRequest)) {
            return null;
        }
        //查询数据
        List<User> userList = userService.list();
        //进行用户脱敏
        List<User> safetyUsers = userList.stream().map(user -> {
            return userService.getSafetyUser(user);
        }).collect(Collectors.toList());
        model.addAttribute("users",safetyUsers);
        return "table/user_table";
    }
    @PostMapping("/add")
    public String add(User user,HttpServletRequest httpServletRequest) {
        //验证角色权限 是否为管理员
        if (!isAdmin(httpServletRequest)) {
            return null;
        }
        //判断参数是否为空
        if (user == null) {
            return null;
        }
        //判断用户是否为空
        if (userService.saveUser(user) == null) {
            //用户为空，返回添加用户将页面
            return "add_user";
        }
        //返回用户信息页面
        return "redirect:/user/list";
    }
    @GetMapping("/search/{id}")
    public String getById(@PathVariable Integer id,Model model) {
        //判断id是否为空
        if (id == null) {
            return null;
        }
        //根据id,获取用户
        User user = userService.getById(id);
        //用户脱敏后返回
        user = userService.getSafetyUser(user);
        if (user == null) {
            return null;
        }
        model.addAttribute("user",user);
        return "update/update_user";
    }
    @PutMapping("/update")
    public String update(User user) {
        //判断参数是否为空
        if (user == null) {
            return null;
        }
        //修改用户信息
        if (!userService.updateUser(user)) {
            return null;
        }
        return "redirect:/user/list";
    }

    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        //判断id是否为空
        if (id == null) {
            return null;
        }
        if (!userService.removeById(id)) {
            return null;
        }
        return "redirect:/user/list";
    }

    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        Object attribute = httpSession.getAttribute(UserConstant.USER_LOGIN_STATE);
        if (attribute != null) {
            httpSession.removeAttribute(UserConstant.USER_LOGIN_STATE);
        }
        return "redirect:/";
    }
    @GetMapping("/searchWith")
    public String searchWith(UserSearchRequest userSearchRequest,Model model) {
        //判断用户是否有查询条件
        String userEncode = userSearchRequest.getUserEncode();
        String username = userSearchRequest.getUsername();
        if (StringUtils.isAllBlank(userEncode,username)) {
            //查询为空，转发到列表接口
            return "forward:/user/list";
        }
        //根据条件查询数据
        List<User> users = userService.searchByCondition(userSearchRequest);
        //用户数据脱敏
        List<User> safetyUsers = users.stream().map(user -> {
            return userService.getSafetyUser(user);
        }).collect(Collectors.toList());
        model.addAttribute("users",safetyUsers);
        return "table/user_table";
    }

    /**
     * 是否为管理员
     * @param httpServletRequest
     * @return
     */
    private boolean isAdmin(HttpServletRequest httpServletRequest) {
        User user = (User) httpServletRequest.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        return user != null && UserConstant.ADMIN.equals(user.getUserRole());
    }


}
